package com.jjb.common.ability.adapter.util;

import org.springframework.aop.framework.AdvisedSupport;
import org.springframework.aop.framework.AopProxy;
import org.springframework.aop.support.AopUtils;
import org.springframework.context.ApplicationContext;

import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;

public class ApplicationBeanUtil {

    // 根据传入的自定义注解的类,从Application获取有此注解的所有类
    public static Map<String, Object> getMapbeanwithAnnotion(ApplicationContext applicationContext, Class<? extends Annotation> cls) {
        Map<String, Object> map = new HashMap<String, Object>();
        map = applicationContext.getBeansWithAnnotation(cls);
        return map;
    }

    // 通过反射操作获取对应的类
    public static Object getTarget(Object proxy) throws RuntimeException {
        if (!AopUtils.isAopProxy(proxy)) {
            return proxy;// 不是代理对象
        }
        try {
            // 根据jdk进行反射操作
            if (AopUtils.isJdkDynamicProxy(proxy)) {
                return getJdkDynamicProxyTargetObject(proxy);
            } else { // 根据cglib进行反射操作
                return getCglibProxyTargetObject(proxy);
            }
        }catch (Exception e) {
            throw new RuntimeException(e);
        }

    }

    private static Object getCglibProxyTargetObject(Object proxy) throws Exception {
        Field h = proxy.getClass().getDeclaredField("CGLIB$CALLBACK_0");
        h.setAccessible(true);
        Object dynamicAdvisedInterceptor = h.get(proxy);
        Field advised = dynamicAdvisedInterceptor.getClass().getDeclaredField("advised");
        advised.setAccessible(true);
        Object target = ((AdvisedSupport) advised.get(dynamicAdvisedInterceptor)).getTargetSource().getTarget();
        return target;
    }

    private static Object getJdkDynamicProxyTargetObject(Object proxy) throws Exception {
        Field h = proxy.getClass().getSuperclass().getDeclaredField("h");
        h.setAccessible(true);
        AopProxy aopProxy = (AopProxy) h.get(proxy);
        Field advised = aopProxy.getClass().getDeclaredField("advised");
        advised.setAccessible(true);
        Object target = ((AdvisedSupport) advised.get(aopProxy)).getTargetSource().getTarget();
        return target;
    }
}
